<?php

namespace app\api\controller;

use app\api\extend\Openssl;
use app\api\extend\Response;
use app\api\middleware\Auth;
use think\App;

class BaseController extends \app\BaseController
{
    const PAGE_SIZE = 10;
	// 中间件
	protected $middleware = [
		Auth::class,
    ];

	public function __construct(App $app)
	{
		parent::__construct($app);
	}

    public function getUserId() {
        $userId = request()->middleware('userId');
        if(!$userId) {
            \Debug::setDebug('请先登录');
        }
        return $userId;
    }

	public function setError($msg='失败', $code=500, $data=[]) {
        if($data == []) {
            $data = new \stdClass();
        }
		return json(Response::setError($msg, $code, $data));
	}

    public function setErrorDefault($msg='失败', $code=500, $data=[]) {
        return $this->setError($msg, $code, $data);
    }

    public function setErrorRequest($msg='失败', $code=400, $data=[]) {
        return $this->setError($msg, $code, $data);
    }

	public function setSuccess($data=[], $code=0) {
		if($data instanceof \ListWithCountStruct) {
			$count = $data->getCount();
			$data = $data->getList();
            return json(Response::setSuccessWithCount($data, $count, $code));
		}

        // 如果是单个值,则追加个value的key
        if(is_int($data) or is_string($data) or is_bool($data)) {
            $data = [
                'value' => $data,
            ];
        }

        // 如果是空数组,则改为空对象
        if($data == []) {
            $data = new \stdClass();
        }
		return json(Response::setSuccess($data, $code));
	}
}